<?php

namespace App\Http\Controllers;

use App\User;

class UserController extends Controller{
    public function index(){
        $params = [
            'username' => (string)request('username'),
        ];
        $lists = User::where(function ($query) use ($params) {
            if ($params['username']) {
                    $query ->where('username','like','%' . $params['username'] . '%');
                }
            })
            ->orderBy('created_at', 'desc')
            ->paginate(10);
        return $this->returnJson(0,'',$lists);
    }

    public function info(){
        $user = auth()->guard('api')->user();
        return $this->returnJson(0,'',$user);
    }

    public function update(){
        $data = request()->all();
        if($data['id']){
            $info = User::find($data['id']);
            if(!$info){
                return $this->returnJson(1,'数据不存在');
            }
            if($data['password']){
                $data['password'] = bcrypt($data['password']);
            }else{
                unset($data['password']);
            }
            if($info->update($data)){
                return $this->returnJson(0,'修改用户成功');
            }
            return $this->returnJson(1,'修改用户失败');
        }else{
            $user = User::where('username',$data['username'])->first();
            if($user){
                return $this->returnJson(1,'该账号已经存在');
            }
            if(empty($data['password'])) $data['password'] = '123456';
            $result = User::register($data);
            if($result){
                return $this->returnJson(0,'添加用户成功');
            }
            return $this->returnJson(1,'添加用户失败');
        }

        auth()->guard('api')->user()->update($data);
        return $this->returnData(auth()->guard('api')->user());
    }


    public function destroy(){
        $id = request('id');
        if(User::destroy($id)){
            return $this->returnJson(0,'删除用户成功');
        }
        return $this->returnJson(1,'删除用户失败');
    }

    public function all(){
        $lists = User::orderBy('id', 'desc')->where('id','>',1)
            ->get()->pluck('nickname','id');
        return $this->returnJson(0,'',$lists);
    }







}